package com.tianhui.consignortwofei.mvp.ui.activity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonView;
import com.fgs.common.appStatus.AppStatusConstant;
import com.fgs.common.appStatus.AppStatusManager;
import com.fgs.common.interf.OnDialogClickListener;
import com.fgs.common.manager.CommonSharedPreferenceManager;
import com.fgs.common.permission.OnPermissionCheckResult;
import com.fgs.common.permission.PermissionHelper;
import com.fgs.common.update.OnUpdateCallback;
import com.fgs.common.update.UpdateContext;
import com.fgs.common.utils.EquipmentUtil;
import com.fgs.common.utils.PackageUtil;
import com.fgs.common.utils.SkipCountDownTimer;
import com.fgs.common.widget.AgreementDialog;
import com.tianhui.consignortwofei.BuildConfig;
import com.tianhui.consignortwofei.MyApplication;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.update.ConsignorCheckUpdate;
import com.tianhui.consignortwofei.widget.ChartBarView;
import com.xuexiang.xutil.net.NetworkUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/3/27
 **/
//public class SplashActivity extends BaseActivity implements OnUpdateCheckCallback {
public class SplashActivity extends BaseActivity {

    @BindView(R.id.activity_splash_bgImageView)
    ImageView bgImageView;
    @BindView(R.id.activity_splash_skipTextView)
    TextView skipTextView;
    @BindView(R.id.activity_splash_downloadProgressTextView)
    TextView downloadProgressTextView;

    private SkipCountDownTimer skipCountDownTimer;

    @Override
    public int getLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public boolean isShowToolbar() {
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AppStatusManager.getInstance().setAppStatus(AppStatusConstant.STATUS_NORMAL);
        getWindow().setBackgroundDrawable(null);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void init() {

        splashInit();
    }

    //隐私协议
    private void splashInit() {
        if (!getAgreeStatus()) {
            new AgreementDialog(this, new OnDialogClickListener() {
                @Override
                public void onPositiveClick() {
                    initBaiDu();
                    requestPermission();
//                    updateOrStart();
                }

                @Override
                public void onNegativeClick(boolean isForce) {
                    finish();
                }
            }).show();
        } else {
            initBaiDu();
            updateOrStart();
        }
    }



    private void initBaiDu(){

        try {

            SDKInitializer.setAgreePrivacy(getApplicationContext(), true);
            //在使用SDK各组件之前初始化context信息，传入ApplicationContext
            SDKInitializer.initialize(getApplicationContext());
            //自4.3.0起，百度地图SDK所有接口均支持百度坐标和国测局坐标，用此方法设置您使用的坐标类型.
            //包括BD09LL和GCJ02两种坐标，默认是BD09LL坐标。
            SDKInitializer.setCoordType(CoordType.BD09LL);



            StringBuilder stringBuilder = new StringBuilder();
    //        stringBuilder.append("manufacturer:");
            stringBuilder.append(EquipmentUtil.getDeviceBrand());
            stringBuilder.append(";");
    //        stringBuilder.append("model:");
            stringBuilder.append(EquipmentUtil.getSystemModel());
            stringBuilder.append(";");
    //        stringBuilder.append("version:");
            stringBuilder.append(EquipmentUtil.getSystemVersion());
            stringBuilder.append(";");
    //        stringBuilder.append("app:");
            stringBuilder.append(PackageUtil.getVersionName(getApplicationContext()));
            stringBuilder.append(";");
            stringBuilder.append("IMEI:");
    //        stringBuilder.append(EquipmentUtil.getIMEI(getApplicationContext()));
            stringBuilder.append(";");
            CommonSharedPreferenceManager.getInstance().setPhoneInfo(stringBuilder.toString());



            disableAPIDialog();
            //因为Android P行为变更，不可多进程使用同一个目录webView，需要为不同进程webView设置不同目录
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                MyApplication application = (MyApplication)getApplication();
                String processName = application.getProcessName(getApplicationContext());
                if (!"com.fgs.common".equals(processName)) {//判断不等于默认进程名称
                    WebView.setDataDirectorySuffix(processName);
                }
            }

    }catch (Exception e){
        Log.e("fei",e.toString());
    }

    }

    private void updateOrStart() {
        if (isNetWorkAvailable()) {
            updateCheck();
        } else {
            startTimer();
        }
    }

    private void requestPermission() {
        new PermissionHelper().checkPermissions(getContext(), Manifest.permission.READ_PHONE_STATE, new OnPermissionCheckResult() {
            @Override
            public void grantedResult() {
                updateOrStart();
            }

            @Override
            public void shouldShowRequestPermissionRationale() {
                updateOrStart();
            }

            @Override
            public void grantedForbidResult() {
                updateOrStart();
            }
        });
    }

    private boolean isNetWorkAvailable() {
        return NetworkUtils.isNetworkAvailable() && NetworkUtils.isHaveInternet();
    }

    ////是否同意相关协议
    private boolean getAgreeStatus() {
        return CommonSharedPreferenceManager.getInstance().getAgreement();
    }


    private void updateCheck() {
        UpdateContext updateContext;
        if (BuildConfig.FLAVOR.equals("officer")) {
            startTimer();
//            updateContext = new UpdateContext(new CheckUpdateByPGY());
        } else {
            updateContext = new UpdateContext(new ConsignorCheckUpdate());


            updateContext.checkUpdate(getContext(), new OnUpdateCallback() {
                @Override
                public void updating(String progress) {
                    if (downloadProgressTextView != null) {
                        downloadProgressTextView.setText("下载进度：" + progress);
                    }
                }

                @Override
                public void updateFailed() {
                    showToast("下载失败");
                }

                @Override
                public void updateFinish() {
                    finish();
                }

                @Override
                public void checkFailed() {
                    startTimer();
                }

                @Override
                public void withoutUpdate() {
                    startTimer();
                }

                @Override
                public void exitUpdate() {
                    finish();
                }
            });

        }


    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    private void startTimer() {
//        skipCountDownTimer = new SkipCountDownTimer(skipTextView, 3100, 1000);
//        skipCountDownTimer.start();
        if (skipTextView != null) {
            skipCountDownTimer = new SkipCountDownTimer(skipTextView, 1100, 1000);
//            skipCountDownTimer = new SkipCountDownTimer(skipTextView, 3100, 1000);
            skipCountDownTimer.start();
            skipTextView.setVisibility(View.GONE);
        }
    }


    private void login() {
//        openActivity(LoginActivity.class);
        openActivity(LoginActivityNew.class);
        finish();
    }

    private void enterHome() {
        String phone = SharedPreferenceManager.getInstance().getPhone();
        if ("18833838825".equals(phone)){
            //报价列表
            Bundle bundle=new Bundle();
            bundle.putInt("lookType",2);
            openActivity(OnlyLookQuotListTwoActivity.class,bundle);
        }else {
            openActivity(MainActivity.class);
        }
        finish();
    }


    @OnClick(R.id.activity_splash_skipTextView)
    public void skip() {
        if (skipCountDownTimer != null) {
            skipCountDownTimer.timeCancel();
        }


        enter();

    }

    private void enter() {
//        String token ="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE4MDE3MjUzNDk5MTgsInVzZXJJZCI6MSwidXVpZCI6IjkzNzczYjNiLWYxNjMtNGU5Mi1iNzI4LWFlZGY3ZjM1NWRjZiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.WOH1ZAF2sg0XmdMKnDR-VLD6RZLXUhXVhsPlGb45x_s";
//        SharedPreferenceManager.getInstance().setToken(token);
        String token = SharedPreferenceManager.getInstance().getToken();
        if (!TextUtils.isEmpty(token)) {
            enterHome();
        } else {
            login();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (skipCountDownTimer != null) {
            skipCountDownTimer.timeCancel();
        }
    }




    /**
     * 反射 禁止弹窗
     */
    private void disableAPIDialog() {
        if (Build.VERSION.SDK_INT < 28) return;
        try {
            Class aClass = Class.forName("android.content.pm.PackageParser$Package");
            Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
            declaredConstructor.setAccessible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Class clazz = Class.forName("android.app.ActivityThread");
            Method currentActivityThread = clazz.getDeclaredMethod("currentActivityThread");
            currentActivityThread.setAccessible(true);
            Object activityThread = currentActivityThread.invoke(null);
            Field mHiddenApiWarningShown = clazz.getDeclaredField("mHiddenApiWarningShown");
            mHiddenApiWarningShown.setAccessible(true);
            mHiddenApiWarningShown.setBoolean(activityThread, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






}
